package com.baidu.treadCommunication;

/**
 * 线程通信案例
 */
public class Account {

    private String id;
    private double money;

    /**
     * 取钱方法
     * @param money
     * @throws Exception
     */
    public synchronized void drawMoney(double money) throws Exception {
        //1.查看取钱的线程名称
        String name = Thread.currentThread().getName();

        //2.判断余额是否够
        if(this.money >= money){
            //2.1.够就取钱
            System.out.println(name + "取钱" + money);
            //2.2.修改账户余额
            this.money -= money;

            //2.3.然后激活其他线程 通知存钱
            this.notifyAll();
            //2.4.将自己睡眠
            this.wait();
        }else {
            //System.out.println(name + "来取钱，但是余额不足");
            //2.5.将其他线程唤醒 来取钱或者存钱
            this.notifyAll();
            this.wait();
        }
    }

    /**
     * 存钱方法 若余额有钱 则不再存入
     * @param money
     * @throws Exception
     */
    public synchronized void saveMoney(double money) throws Exception {
        //1.获取调用该方法的线程名称
        String name = Thread.currentThread().getName();
        //2.判断是否有钱 有钱则不存入
        if(this.money > 0){
            //System.out.println(name + "来存钱了,但是发现余额还有");
            this.notifyAll();
            this.wait();
        }else {
            //2.1.如果没钱 则存入
            System.out.println(name + "来存钱了" + money);
            this.money += money;
            //2.2.存完后唤醒其他线程来取钱 或者 存钱
            this.notifyAll();
            this.wait();
        }
    }

    public Account() {
    }

    public Account(String id, double money) {
        this.id = id;
        this.money = money;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}
